#!/usr/bin/env bash
set -euo pipefail
# build.sh - 在本地或 CI 中构建三个变体并打包为 zip
# 使用方法: 在仓库根目录运行 ./build.sh

REPO_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$REPO_DIR"

# repo name
REPO_NAME="${PWD##*/}"

# try to get an exact tag for current commit, else use timestamped local tag
TAG="$(git describe --tags --exact-match 2>/dev/null || echo "local-$(date +%Y%m%d%H%M%S)")"
PACKAGE="${REPO_NAME}-${TAG}"

echo "Repository: $REPO_NAME"
echo "Tag/Package: $PACKAGE"
echo "Working dir: $REPO_DIR"

build_variant() {
  variant_suffix="$1" # e.g. mixly2.0rc3 or mixly1.0; empty for default
  build_cmd="$2"
  out_name="${PACKAGE}"
  if [ -n "$variant_suffix" ]; then
    out_name="${PACKAGE}_${variant_suffix}"
  fi

  echo "\n=== Building ${out_name} with: ${build_cmd} ==="
  # install deps (idempotent-ish)
  npm install

  # run the build command
  eval "$build_cmd"

  # produce zip from dist/sentry3-mixly
  if [ -d dist/sentry3-mixly ]; then
    (cd dist && zip -r "$REPO_DIR/${out_name}.zip" sentry3-mixly)
    echo "Created: ${out_name}.zip"
  else
    echo "Error: dist/sentry3-mixly not found after build (expected path: dist/sentry3-mixly)"
    exit 1
  fi
}

# Default build
build_variant "" "npm run build:prod"

# 2.0rc3 build
build_variant "mixly2.0rc3" "npm run build:prod:2.0rc3"

# 1.0 build
build_variant "mixly1.0" "npm run build:prod:1.0"

echo "\n=== Build finished. Artifacts: ==="
ls -lh "$REPO_DIR"/*.zip || true

echo "Done. If you want to upload these to Gitee releases, set GITEE_TOKEN and use the workflow or curl API."
